package cn.bugstack.chatgpt.data.domain.order.service;

import cn.bugstack.chatgpt.data.domain.order.model.entity.*;
import cn.bugstack.chatgpt.data.domain.order.model.valobj.PayStatusVO;
import cn.bugstack.chatgpt.data.domain.order.repository.IOrderRepository;
import cn.bugstack.chatgpt.data.types.common.Constants;
import cn.bugstack.chatgpt.data.types.exception.ChatGPTException;
import com.sun.javafx.geom.ConcentricShapePair;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * 关于下单的流程有两部分：
 * 1、对有效的未支付订单进行处理
 * 2、若没有有效的支付订单则从头开始创建下单
 *
 */
@Slf4j
public abstract class AbstractOrderService implements IOrderService {
    @Resource
    protected IOrderRepository orderRepository;

    public PayOrderEntity createOrder(ShopCartEntity shopCartEntity) {
        try {
            // 1. 获得用户微信唯一ID和商品id
            String openid = shopCartEntity.getOpenid();
            Integer productId = shopCartEntity.getProductId();

            // 2. 查询有效的未支付订单，如果存在直接返回微信支付 Native CodeUrl
            UnpaidOrderEntity unpaidOrderEntity = orderRepository.queryUnpaidOrder(shopCartEntity);
            // 2.1 判断是否有有效的未支付订单：有效的未支付订单不为空且订单状态存在等待支付状态
            // 是否有微信支付的url也有两种情况：1、有url，表明已生成微信支付；
            // 2、 无url，需要生成支付单
            if (null != unpaidOrderEntity && PayStatusVO.WAIT.equals(unpaidOrderEntity.getPayStatus()) && null != unpaidOrderEntity.getPayUrl()) {
                log.info("创建订单-存在，已生成微信支付，返回 openid: {} orderId: {} payUrl: {}", openid,
                        unpaidOrderEntity.getOrderId(), unpaidOrderEntity.getPayUrl());
                return PayOrderEntity.builder()
                        .openid(openid)
                        .orderId(unpaidOrderEntity.getOrderId())
                        .payUrl(unpaidOrderEntity.getPayUrl())
                        .payStatus(unpaidOrderEntity.getPayStatus())
                        .build();

            } else if (null != unpaidOrderEntity && null == unpaidOrderEntity.getPayUrl()) {
                // 生成支付单
                log.info("创建订单-存在，未生成微信支付，返回 openid: {} orderId: {}", openid, unpaidOrderEntity.getOrderId());
                PayOrderEntity payOrderEntity = this.doPrepayOrder(openid, unpaidOrderEntity.getOrderId(), unpaidOrderEntity.getProductName(),
                        unpaidOrderEntity.getTotalAmount());
                log.info("创建订单-完成，生成支付单。openid: {} orderId: {} payUrl: {}", openid, payOrderEntity.getOrderId(), payOrderEntity.getPayUrl());
                return payOrderEntity;


            }

            // 若没有有效的未支付订单，则从头来开始创建订单
            // 1. 查询下单的商品，查询是否可用
            ProductEntity productEntity = orderRepository.queryProduct(productId);
            if (!productEntity.isAvailable()){
                // 商品不可用，则抛出异常
                throw new ChatGPTException(Constants.ResponseCode.ORDER_PRODUCT_ERR.getCode(), Constants.ResponseCode.ORDER_PRODUCT_ERR.getInfo());
            }
            // 2.保存订单：商品可用，则保存订单;凭借id和实体进行入单操作
            OrderEntity orderEntity = this.doSaveOrder(openid, productEntity);

            // 3. 创建支付单
            PayOrderEntity payOrderEntity = this.doPrepayOrder(openid, orderEntity.getOrderId(), productEntity.getProductName(), orderEntity.getTotalAmount());
            log.info("创建订单-完成，生成支付单。openid: {} orderId: {} payUrl: {}", openid, orderEntity.getOrderId(), payOrderEntity.getPayUrl());

            return payOrderEntity;
        } catch (Exception e) {
            log.error("创建订单，已生成微信支付，返回 openid: {} productId: {}", shopCartEntity.getOpenid(), shopCartEntity.getProductId());
            throw new ChatGPTException(Constants.ResponseCode.UN_ERROR.getCode(), Constants.ResponseCode.UN_ERROR.getInfo());
        }



    }

    protected abstract OrderEntity doSaveOrder(String openid, ProductEntity productEntity);

    protected abstract PayOrderEntity doPrepayOrder(String openid, String orderId, String productName, BigDecimal amountTotal);
}
